package com.joinway.framework.support.security.validator;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.CollectionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.joinway.framework.bean.constant.ErrorCodeConstants;
import com.joinway.framework.bean.exception.ValidationException;
import com.joinway.framework.bean.security.type.CheckPoint;

public class RequestHeaderValidator implements ISecurityValidator {

	private final static Logger log = LoggerFactory.getLogger(RequestHeaderValidator.class);
			
	protected String key = "";
	protected String value = "";
	protected List<String> whiteHostList;
	
	public RequestHeaderValidator(String key, String value) {
		this.key = key;
		this.value = value;
	}

	@Override
	public void validate(ProceedingJoinPoint point) throws ValidationException {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		
		String ip = request.getRemoteAddr();
		if(CollectionUtils.isNotEmpty(whiteHostList) && !whiteHostList.contains(ip)){
			String v = request.getHeader(key);
			if(!value.equals(v)){
				throw new ValidationException(ErrorCodeConstants.INVALID_REQUEST_HEADER_DESC);
			}
		}
		
	}

	@Override
	public CheckPoint getCheckPoint() {
		return CheckPoint.Header;
	}

	public List<String> getWhiteHostList() {
		return whiteHostList;
	}

	public void setWhiteHostList(List<String> whiteHostList) {
		this.whiteHostList = whiteHostList;
	}

}
